package com.gree.shyun.util;


import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.nio.file.Paths;
import java.util.*;

import com.gree.shyun.bean.View;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * JSON对象与XML相互转换工具类
 * android xml布局与json互转
 */
public class JsonXmlUtils {

    private static final String ENCODING = "UTF-8";

    /**
     * JSON对象转漂亮的xml字符串
     *
     * @param json JSON对象
     * @return 漂亮的xml字符串
     * @throws IOException
     * @throws SAXException
     */
    public static String jsonToPrettyXml(JSONObject json) throws IOException, SAXException {
        Document document = jsonToDocument(json);

        /* 格式化xml */
        OutputFormat format = OutputFormat.createPrettyPrint();
        // 设置缩进为4个空格
        format.setIndent(" ");
        format.setIndentSize(4);
        format.setIndent(true);
        StringWriter formatXml = new StringWriter();
        XMLWriter writer = new XMLWriter(formatXml, format);
        writer.write(document);

        return formatXml.toString();
    }

    /**
     * JSON对象转xml字符串
     *
     * @param json JSON对象
     * @return xml字符串
     * @throws SAXException
     */
    public static String JsonToXml(JSONObject json) throws SAXException {
        return jsonToDocument(json).asXML();
    }

    /**
     * JSON对象转Document对象
     *
     * @param json JSON对象
     * @return Document对象
     * @throws SAXException
     */
    public static Document jsonToDocument(JSONObject json) throws SAXException {
        Document document = DocumentHelper.createDocument();
        document.setXMLEncoding(ENCODING);

        // root对象只能有一个
        for (String rootKey : json.keySet()) {
            Element root = jsonToElement(json.getJSONObject(rootKey), rootKey);
            document.add(root);
            break;
        }
        return document;
    }
    /**
     * JSON对象转Element对象
     *
     * @param json JSON对象
     * @param nodeName 节点名称
     * @return Element对象
     */
    public static Element jsonToElement(JSONObject json, String nodeName) {
        Element node = DocumentHelper.createElement(nodeName);
        for (String key : json.keySet()) {
            Object child = json.get(key);
            if (child instanceof JSONObject) {
                String name = key;
                if(key.contains("[")) {
                    name = key.substring(0, key.lastIndexOf("["));
                }
                node.add(jsonToElement(json.getJSONObject(key), name));
            }else if(child instanceof JSONArray) {
                JSONArray array = (JSONArray) child;
                for(int i = 0;i<array.size();i++){
                    JSONObject jsonObject = array.getJSONObject(i);
                    String name = "";
                    for(String k:jsonObject.keySet()){
                        if(k.startsWith("&",0)){
                            name  = k.substring(1);
                            break;
                        }
                    }
                    node.add(jsonToElement(jsonObject, name));
                }
            }else {
                if(key.startsWith("@",0)){
                    String value =  json.getString(key);
                    key = key.substring(1);
                    if(key.contains("[")) {
                        key = key.substring(0, key.lastIndexOf("["));
                    }
                    node.addAttribute(key, value);
                }else{
                    Element element = DocumentHelper.createElement(key);
                    element.setText(json.getString(key));
                    node.add(element);
                }
            }
        }
        return node;
    }

    /**
     * XML字符串转JSON对象
     *
     * @param xml xml字符串
     * @return JSON对象
     * @throws DocumentException
     */
    public static JSONObject xmlToJson(String xml) throws DocumentException {
        JSONObject json = new JSONObject(true);

        SAXReader reader = new SAXReader();
        Document document = reader.read(new StringReader(xml));
        Element root = document.getRootElement();

        JSONObject child =  elementToJson(root);
        for(Object obj:root.declaredNamespaces()){
            Namespace ns = (Namespace) obj;
            child.put("@xmlns:"+ns.getPrefix(),ns.getStringValue());
        }
        for(int i=0;i< root.attributeCount();i++){
            Attribute attr = root.attribute(i);
            child.put("@"+attr.getNamespacePrefix()+":"+attr.getName(),attr.getValue());
        }
        json.put(root.getName(),child);
        return json;
    }

    /**
     * Element对象转JSON对象
     *
     * @param element Element对象
     * @return JSON对象
     */
    public static JSONObject elementToJson(Element element) {
        JSONObject json = new JSONObject(true);
        Map<Integer,Element> ele = new LinkedHashMap<>();
        Map<Integer,Map<String,Object>> allattr = new LinkedHashMap<>();
        for (int a = 0 ; a<  element.elements().size();a++) {
            Element e = (Element) element.elements().get(a);
            if (e.elements().isEmpty()) {
                Map<String,Object> attrs = new LinkedHashMap<>();
                for(int i=0;i< e.attributeCount();i++){
                    Attribute attr = e.attribute(i);
                    attrs.put("@"+attr.getNamespacePrefix()+":"+attr.getName()+"["+a+":"+i,attr.getValue());
                }
                json.put(e.getName()+"["+a,JSON.toJSON(attrs));
            }else {
                Map<String,Object> attrs = new LinkedHashMap<>();
                for(int i=0;i< e.attributeCount();i++){
                    Attribute attr = e.attribute(i);
                    attrs.put("@"+attr.getNamespacePrefix()+":"+attr.getName()+"["+a+":"+i,attr.getValue());
                }
                ele.put(a,e);
                allattr.put(a,attrs);
            }
        }
        List<JSONObject> list = new ArrayList<>();
        for(Integer key:ele.keySet()) {
            Element e = ele.get(key);
            Map<String, Object> attrs = allattr.get(key);
            //另创一个有序map
            JSONObject jsonObject = new JSONObject(true);
            jsonObject.putAll(elementToJson(e));
            jsonObject.putAll(attrs);
            list.add(jsonObject);
        }

        json.put("&" + element.getName(), JSON.toJSON(list));
        return json;
    }

    /**
     * 文件内容转换成字符串
     *
     * @param filePath 文件路径
     * @return 内容字符串
     * @throws IOException
     */
    public static String fileToString(URL filePath) throws IOException {
        return IOUtils.toString(filePath, ENCODING);
    }

    /**
     * 文件内容转换成字符串
     *
     * @param filePath 文件路径
     * @return 内容字符串
     * @throws IOException
     */
    public static String fileToString(String filePath) throws IOException {
        return IOUtils.toString(Paths.get(filePath).toUri(), ENCODING);
    }

    /**
     * 字符串输出到文件
     *
     * @param str 字符串内容
     * @param filePath 文件路径
     * @throws IOException
     */
    public static void stringToFile(String str, String filePath) throws IOException {
        FileUtils.writeStringToFile(Paths.get(filePath).toFile(), str, ENCODING);
    }

    /**
     * 字符串输出到文件
     *
     * @param str 字符串内容
     * @param filePath 文件路径
     * @throws IOException
     */
    public static void stringToFile(String str, URL filePath) throws IOException {
        FileUtils.writeStringToFile(new File(filePath.getPath()), str, ENCODING);
    }

    /**
     * 字符串输出到文件
     *
     * @param str 字符串内容
     * @param file 输出文件
     * @throws IOException
     */
    public static void stringToFile(String str, File file) throws IOException {
        FileUtils.writeStringToFile(file, str, ENCODING);
    }


    /**
     *  json 转view
     * @param json
     * @return
     */
    public static View jsonToView(JSONObject json, String nodeName) {
        View node = new View();
        node.setName(nodeName);
        for (String key : json.keySet()) {
            Object child = json.get(key);
            if (child instanceof JSONObject) {
                String name = key;
                if(key.contains("[")) {
                    name = key.substring(0, key.lastIndexOf("["));
                }
                node.add(jsonToView(json.getJSONObject(key), name));
            }else if(child instanceof JSONArray) {
                JSONArray array = (JSONArray) child;
                for(int i = 0;i<array.size();i++){
                    JSONObject jsonObject = array.getJSONObject(i);
                    String name = "";
                    for(String k:jsonObject.keySet()){
                        if(k.startsWith("&",0)){
                            name  = k.substring(1);
                            break;
                        }
                    }
                    node.add(jsonToView(jsonObject, name));
                }
            }else {
                if(key.startsWith("@",0)){
                    String value =  json.getString(key);
                    key = key.substring(1);
                    if(key.contains("[")) {
                        key = key.substring(0, key.lastIndexOf("["));
                    }
                    node.addAttribute(key, value);
                    if("android:id".equals(key)){
                        node.setId(value.substring(value.indexOf("/")+1));
                    }
                }else{
                    View  element = new View();
                    element.setName(key);
                    node.add(element);
                }
            }
        }
        return node;
    }

    /**
     *  jsonToView
     * @param json
     * @return
     */
    public static View jsonToView(JSONObject json)  {
        View view = new View();
        view.setName("root");
        // root对象只能有一个
        for (String rootKey : json.keySet()) {
            View root = jsonToView(json.getJSONObject(rootKey), rootKey);
            view.add(root);
            break;
        }
        return view;
    }

    /**
     * 获取view
     * @param path
     * @return
     */
    public static View getViewFromPath(String path){
        try {
            String xml = fileToString(path);
            JSONObject object = xmlToJson(xml);
            return jsonToView(object);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}